import { _getTicket } from '../../common/parking'
const app = getApp()
Page({
  data: {
    openid: '',
    res: '',
    msg: '',
    fromScan: false,
    count: 5
  },
  timer: null,
  getTicket() {
    let code = this.data.code
    let openid = this.data.openid
    app.loading('加载中')
    _getTicket(openid, code).then(res => {
      wx.hideLoading()
      if (res.data.IsSuccess) {
        this.setData({
          res: true
        })
      } else {
        this.setData({
          res: false
        })
      }
      this.setData({
        msg: res.data.Msg
      })
      // this.countDown()
    }).catch(err => {
      console.log(err)
      wx.hideLoading()
      this.setData({
        res: false
      })
      wx.showModal({
        title: '对不起',
        content: '请求错误，请稍后再试',
        showCancel: false
      })
    })
  },
  countDown () {
    let { count } = this.data
    this.timer = setInterval(() => {
      if (count <= 1) {
        clearInterval(this.timer)
        this.timer = null
        if (this.data.res) {
          wx.redirectTo({
            url: '/pages/parking/query'
          })
        } else {
          wx.switchTab({
            url: '/pages/home/index'
          })
        }
      }
      count -= 1
      this.setData({
        count
      })
    }, 1000)
  },
  onLoad (options) {
    console.log('trigger onload')
    if (this.timer) {
      clearInterval(this.timer)
      this.setData({
        count: 5
      })
    }
    console.log(options)
    const fromScan = options.scene
    this.data.fromScan = fromScan
    if (!fromScan) {
      this.data.res = options.res === '0' ? false : true
      this.setData({
        res: this.data.res
      }, () => {
        this.countDown()
      })
    } else {
      const code = decodeURIComponent(options.scene)
      this.data.code = code
    }
  },
  onReady () {},
  onShow () {
    console.log('trigger onshow')
    if (this.timer) {
      clearInterval(this.timer)
      this.setData({
        count: 5
      })
    }
    app.memberReadyCb = () => {
    }
    app.fansReadyCb = () => {
      this.data.openid = app.globalData.fans.AppOpenID
      if (this.data.code) {
        this.getTicket()
      }
      // app.checkMember()
    }
    app.init()
  },
  onHide () {
  },
  onShareAppMessage() {
    return app.shareInfo
  }
})